/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.estoque.Telas;

import br.com.estoque.Fornecedores.Fornecedor;
import br.com.estoque.Fornecedores.FornecedorDAO;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author note
 */
public class Fornecedores extends javax.swing.JFrame {

    DefaultTableModel tmFornecedores = new DefaultTableModel(null, new String[]{"Código", "Nome","Endereço",  "Telefone"});
    List<Fornecedor> fornecedores;
    ListSelectionModel lsmFornecedores;
    String tipoCadastro;
    
    /**
     * Creates new form Fornecedores
     */
    public Fornecedores() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tfFornecedores = new javax.swing.JTextField();
        botaoPesquisaFornecedores = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbFornecedores = new javax.swing.JTable();
        labelNome = new javax.swing.JLabel();
        tfNomeFornecedor = new javax.swing.JTextField();
        labelTelefoneFornecedor = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        botaoNovoFornecedor = new javax.swing.JButton();
        botaoSalvarFornecedor = new javax.swing.JButton();
        botaoAlterarFornecedor = new javax.swing.JButton();
        botaoCancelarFornecedor = new javax.swing.JButton();
        botaoFecharFornecedor = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        tfCNPJ = new javax.swing.JFormattedTextField();
        tfTelefone = new javax.swing.JFormattedTextField();
        jLabel3 = new javax.swing.JLabel();
        tfEndereco = new javax.swing.JTextField();
        tfBairro = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        tfCidade = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        tfUF = new javax.swing.JTextField();
        tfCEP = new javax.swing.JTextField();

        setTitle("Fornecedores");

        botaoPesquisaFornecedores.setText("Pesquisar");
        botaoPesquisaFornecedores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoPesquisaFornecedoresActionPerformed(evt);
            }
        });

        tbFornecedores.setModel(tmFornecedores);
        tbFornecedores.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmFornecedores = tbFornecedores.getSelectionModel();
        lsmFornecedores.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e){
                if(! e.getValueIsAdjusting()){
                    tbFornecedoresLinhaSelecionada(tbFornecedores);
                }
            }
        });
        jScrollPane1.setViewportView(tbFornecedores);

        labelNome.setText("Nome: *");

        tfNomeFornecedor.setEditable(false);
        tfNomeFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfNomeFornecedorActionPerformed(evt);
            }
        });

        labelTelefoneFornecedor.setText("Telefone:");

        jLabel1.setText("*: Campos com preenchimento obrigatório");

        botaoNovoFornecedor.setText("Novo");
        botaoNovoFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoNovoFornecedorActionPerformed(evt);
            }
        });

        botaoSalvarFornecedor.setText("Salvar");
        botaoSalvarFornecedor.setEnabled(false);
        botaoSalvarFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoSalvarFornecedorActionPerformed(evt);
            }
        });

        botaoAlterarFornecedor.setText("Alterar");
        botaoAlterarFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAlterarFornecedorActionPerformed(evt);
            }
        });

        botaoCancelarFornecedor.setText("Cancelar");
        botaoCancelarFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCancelarFornecedorActionPerformed(evt);
            }
        });

        botaoFecharFornecedor.setText("Fechar");
        botaoFecharFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoFecharFornecedorActionPerformed(evt);
            }
        });

        jLabel2.setText("CNPJ:");

        tfCNPJ.setEditable(false);
        try {
            tfCNPJ.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###.###/####-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        tfTelefone.setEditable(false);
        try {
            tfTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        jLabel3.setText("Endereço: ");

        tfEndereco.setEditable(false);
        tfEndereco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfEnderecoActionPerformed(evt);
            }
        });

        tfBairro.setEditable(false);

        jLabel4.setText("Bairro:");

        tfCidade.setEditable(false);

        jLabel5.setText("Cidade:");

        jLabel6.setText("UF:");

        jLabel7.setText("CEP:");

        tfUF.setEditable(false);

        tfCEP.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(150, 150, 150)
                        .addComponent(botaoFecharFornecedor)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(tfFornecedores)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoPesquisaFornecedores))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tfNomeFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(labelNome)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel5)
                                            .addComponent(tfCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(tfUF, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jLabel6))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel7)
                                            .addComponent(tfCEP, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(4, 4, 4)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(tfCNPJ, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tfTelefone, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(labelTelefoneFornecedor, javax.swing.GroupLayout.Alignment.LEADING)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(botaoNovoFornecedor)
                                .addGap(18, 18, 18)
                                .addComponent(botaoSalvarFornecedor)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(botaoAlterarFornecedor)
                                .addGap(18, 18, 18)
                                .addComponent(botaoCancelarFornecedor))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addComponent(tfBairro))))
                        .addContainerGap())))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {botaoAlterarFornecedor, botaoCancelarFornecedor, botaoFecharFornecedor, botaoNovoFornecedor, botaoPesquisaFornecedores, botaoSalvarFornecedor});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfFornecedores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botaoPesquisaFornecedores))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelNome)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfNomeFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelTelefoneFornecedor)
                        .addComponent(jLabel5)
                        .addComponent(jLabel7)))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfCEP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoNovoFornecedor)
                    .addComponent(botaoSalvarFornecedor)
                    .addComponent(botaoAlterarFornecedor)
                    .addComponent(botaoCancelarFornecedor))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botaoFecharFornecedor)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfNomeFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfNomeFornecedorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfNomeFornecedorActionPerformed

    private void botaoFecharFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoFecharFornecedorActionPerformed
        if(JOptionPane.showConfirmDialog(null, "Deseja sair da tela de Fornecedores?", "ATENÇÃO", JOptionPane.YES_NO_OPTION)==0){
            this.hide();
        }
    }//GEN-LAST:event_botaoFecharFornecedorActionPerformed

    private void tfEnderecoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfEnderecoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfEnderecoActionPerformed

    private void botaoNovoFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoNovoFornecedorActionPerformed
        tipoCadastro = "novo";
        novoFornecedor();
    }//GEN-LAST:event_botaoNovoFornecedorActionPerformed

    private void botaoSalvarFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSalvarFornecedorActionPerformed
       if(tipoCadastro.equals("novo")){
           try {
               cadastrarFornecedor();
           } catch (SQLException ex) {
               Logger.getLogger(Fornecedores.class.getName()).log(Level.SEVERE, null, ex);
           }
           try {
               listarFornecedores();
           } catch (SQLException ex) {
               Logger.getLogger(Fornecedores.class.getName()).log(Level.SEVERE, null, ex);
           }
       } else if(tipoCadastro.equals("alterar")){
           try {
               alterarFornecedor();
           } catch (SQLException ex) {
               Logger.getLogger(Fornecedores.class.getName()).log(Level.SEVERE, null, ex);
           }
           try {
               listarFornecedores();
           } catch (SQLException ex) {
               Logger.getLogger(Fornecedores.class.getName()).log(Level.SEVERE, null, ex);
           }
       }
       desabilitarCampos();
    }//GEN-LAST:event_botaoSalvarFornecedorActionPerformed

    private void botaoAlterarFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAlterarFornecedorActionPerformed
        tipoCadastro = "alterar";
        alteraFornecedor();
    }//GEN-LAST:event_botaoAlterarFornecedorActionPerformed

    private void botaoCancelarFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarFornecedorActionPerformed
        if(JOptionPane.showConfirmDialog(null, "Deseja Cancelar esta ação?", "ATENÇÃO", JOptionPane.YES_NO_OPTION)==0){
            desabilitarCampos();
        }
    }//GEN-LAST:event_botaoCancelarFornecedorActionPerformed

    private void botaoPesquisaFornecedoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoPesquisaFornecedoresActionPerformed
        try {
            listarFornecedores();
        } catch (SQLException ex) {
            Logger.getLogger(Fornecedores.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_botaoPesquisaFornecedoresActionPerformed

    
    private void habilitarCampos(){
        tfNomeFornecedor.setEditable(true);
        tfEndereco.setEditable(true);
        tfBairro.setEditable(true);
        tfCEP.setEditable(true);
        tfCNPJ.setEditable(true);
        tfTelefone.setEditable(true);
        tfCidade.setEditable(true);
        tfUF.setEditable(true);
        botaoSalvarFornecedor.setEnabled(true);
        botaoFecharFornecedor.setEnabled(false);  
    }
    private void desabilitarCampos(){
        tfNomeFornecedor.setEditable(false);
        tfEndereco.setEditable(false);
        tfBairro.setEditable(false);
        tfCEP.setEditable(false);
        tfCNPJ.setEditable(false);
        tfTelefone.setEditable(false);
        tfCidade.setEditable(false);
        tfUF.setEditable(false);
        botaoSalvarFornecedor.setEnabled(false);
        botaoAlterarFornecedor.setEnabled(true);
        botaoNovoFornecedor.setEnabled(true);
        botaoFecharFornecedor.setEnabled(true);  
    }
    private void novoFornecedor(){
        botaoAlterarFornecedor.setEnabled(false);
        habilitarCampos();
        tfNomeFornecedor.setText("");
        tfEndereco.setText("");
        tfBairro.setText("");
        tfCEP.setText("");
        tfCNPJ.setText("");
        tfTelefone.setText("");
        tfCidade.setText("");
        tfUF.setText("");
    }
    private boolean verificarCampos(){
        if(!tfNomeFornecedor.getText().trim().equals("")){
            return true;
        }else{
            JOptionPane.showMessageDialog(null,"Campo nome é obrigatório!");
            return false;
        }
    }
    private boolean verificarUF(){
        if(tfUF.getText().length() > 2){
            JOptionPane.showMessageDialog(null, "Campo UF deve possuir apenas 2 Letras!");
            return false;
        } else
             return true;
    }
    private boolean verificarNome(String nome) throws SQLException{
       boolean resultado = false; 
        FornecedorDAO dao = new FornecedorDAO();
        
        fornecedores = dao.listarFornecedores("%"+tfNomeFornecedor+"%");
        
        if(fornecedores.isEmpty()){
            resultado  = true;
        } else {
            JOptionPane.showMessageDialog(null, "Fornecedor com este nome já existente, utilize outro nome!");
            tfNomeFornecedor.requestFocus();
            resultado = false;
        }
       
       return resultado;
    }
    private boolean verificarCNPJ(String cnpj) throws SQLException{
        boolean resultado = false;
        FornecedorDAO dao = new FornecedorDAO();
        
        fornecedores = dao.listarFornecedores("%"+tfCNPJ+"%");
        
        if(fornecedores.isEmpty()){
            resultado  = true;
        } else{
            JOptionPane.showMessageDialog(null, "Fornecedor com este CNPJ já existente, utilize outro CNPJ!");
            tfCNPJ.requestFocus();
            resultado = false;
        }
        
        
        return resultado;
    }
        
    private void cadastrarFornecedor() throws SQLException{
        if(verificarCampos() && verificarUF() && verificarNome("%"+tfNomeFornecedor.getText().trim()+"%")&&verificarCNPJ("%"+tfCNPJ.getText().trim()+"%")){
            Fornecedor forn = new Fornecedor();
            forn.setNome(tfNomeFornecedor.getText().trim());
            forn.setCNPJ(tfCNPJ.getText().trim());
            forn.setCidade(tfCidade.getText().trim());           
            forn.setEndereco(tfEndereco.getText().trim());
            forn.setBairro(tfBairro.getText().trim());
            forn.setCidade(tfCidade.getText().trim());
            forn.setUF(tfUF.getText().trim());
            forn.setCEP(tfCEP.getText().trim());
            forn.setTelefone(tfTelefone.getText().trim());
            FornecedorDAO fornecedor = new FornecedorDAO();
            fornecedor.cadastrarFornecedor(forn);
            JOptionPane.showMessageDialog(null, forn.getNome() + " cadastrado com sucesso");
            desabilitarCampos();
        }
    }
    private void mostrarFornecedores(List<Fornecedor> fornecedores) throws SQLException{
        while(tmFornecedores.getRowCount() > 0){
            tmFornecedores.removeRow(0);
        }
        if(fornecedores.size()==0){
            JOptionPane.showMessageDialog(null,"Nenhum Fornecedor Encontrado!");
        } else{
            String linha[] = new String[]{null,null,null,null};
            for(int i = 0; i<fornecedores.size(); i++){
                tmFornecedores.addRow(linha);
                tmFornecedores.setValueAt(fornecedores.get(i).getCodigo(), i, 0);
                tmFornecedores.setValueAt(fornecedores.get(i).getNome(), i, 1);
                tmFornecedores.setValueAt(fornecedores.get(i).getEndereco(), i, 2);
                tmFornecedores.setValueAt(fornecedores.get(i).getTelefone(), i, 3);
            }
        }
    }
    private void listarFornecedores() throws SQLException{
        FornecedorDAO forn = new FornecedorDAO();
        fornecedores = forn.listarFornecedores("%" + tfFornecedores.getText().trim() + "%");
        mostrarFornecedores(fornecedores);
    }
    private void tbFornecedoresLinhaSelecionada(JTable table){
        if(tbFornecedores.getSelectedRow() != -1){ //retorna -1 quando não há nenhuma linha da tabela selecionada
            tfNomeFornecedor.setText(fornecedores.get(table.getSelectedRow()).getNome());
            tfCNPJ.setText(fornecedores.get(table.getSelectedRow()).getCNPJ());
            tfEndereco.setText(fornecedores.get(table.getSelectedRow()).getEndereco());
            tfBairro.setText(fornecedores.get(table.getSelectedRow()).getBairro());
            tfCidade.setText(fornecedores.get(table.getSelectedRow()).getCidade());
            tfUF.setText(fornecedores.get(table.getSelectedRow()).getUF());
            tfCEP.setText(fornecedores.get(table.getSelectedRow()).getCEP());
            tfTelefone.setText(fornecedores.get(table.getSelectedRow()).getTelefone());
        } else{
            novoFornecedor();
        }
    }
    private void alteraFornecedor(){
        if(tbFornecedores.getSelectedRow()!= -1){
            botaoNovoFornecedor.setEnabled(false);
            habilitarCampos();
        } else{
            JOptionPane.showMessageDialog(this, "Selecione um fornecedor!");
        }
    }
    private void alterarFornecedor() throws SQLException{
         if(verificarCampos()&& verificarUF()){
           Fornecedor forn = new Fornecedor();
           forn.setNome(tfNomeFornecedor.getText().trim()); 
           forn.setCidade(tfCidade.getText().trim());           
           forn.setEndereco(tfEndereco.getText().trim());
           forn.setBairro(tfBairro.getText().trim());
           forn.setCidade(tfCidade.getText().trim());
           forn.setUF(tfUF.getText().trim());
           forn.setCEP(tfCEP.getText().trim());
           forn.setTelefone(tfTelefone.getText().trim());
           forn.setCodigo(fornecedores.get(tbFornecedores.getSelectedRow()).getCodigo());
           FornecedorDAO fornecedor = new FornecedorDAO();
           fornecedor.alterarFornecedor(forn);
           JOptionPane.showMessageDialog(null, forn.getNome()+ " alterado com Sucesso!");
           desabilitarCampos(); 
               
       } 
    }
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Fornecedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Fornecedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Fornecedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Fornecedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Fornecedores().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoAlterarFornecedor;
    private javax.swing.JButton botaoCancelarFornecedor;
    private javax.swing.JButton botaoFecharFornecedor;
    private javax.swing.JButton botaoNovoFornecedor;
    private javax.swing.JButton botaoPesquisaFornecedores;
    private javax.swing.JButton botaoSalvarFornecedor;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelNome;
    private javax.swing.JLabel labelTelefoneFornecedor;
    private javax.swing.JTable tbFornecedores;
    private javax.swing.JTextField tfBairro;
    private javax.swing.JTextField tfCEP;
    private javax.swing.JFormattedTextField tfCNPJ;
    private javax.swing.JTextField tfCidade;
    private javax.swing.JTextField tfEndereco;
    private javax.swing.JTextField tfFornecedores;
    private javax.swing.JTextField tfNomeFornecedor;
    private javax.swing.JFormattedTextField tfTelefone;
    private javax.swing.JTextField tfUF;
    // End of variables declaration//GEN-END:variables
}
